﻿using System.IO.IsolatedStorage;

namespace Chenglin.WPMyStep
{
    public class ApplicationState
    {
        private const string LocationConsentKey = "LocationConsent";
        private const string MovementThresholdKey = "MovementThreshold";
        private static ApplicationState s_state;

        /// <summary>
        /// Indicates whether the location service is allowed by the user.
        /// </summary>
        public bool? LocationConsent { get; set; }

        /// <summary>
        /// Gets the distance of movement, in meters, relative to the coordinate from
        /// the last PositionChanged event, that is required for the Geolocator to raise
        /// a PositionChanged event.
        /// </summary>
        public int MovementThreshold { get; set; }

        public static ApplicationState State
        {
            get
            {
                if (s_state == null)
                {
                    s_state = ReadStateFromStorage();
                }
                return s_state;
            }
        }

        /// <summary>
        /// private constructor
        /// </summary>
        private ApplicationState()
        {
            LocationConsent = false;
            MovementThreshold = 5;
        }

        /// <summary>
        /// Save the settings to the storage.
        /// </summary>
        public void Save()
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (LocationConsent.HasValue)
            {
                settings[LocationConsentKey] = LocationConsent.Value;
            }
            settings[MovementThresholdKey] = MovementThreshold;
            settings.Save();
        }

        private static ApplicationState ReadStateFromStorage()
        {
            var settings = IsolatedStorageSettings.ApplicationSettings;
            ApplicationState state = new ApplicationState();

            bool booleanVal;
            if (settings.TryGetValue(LocationConsentKey, out booleanVal))
            {
                state.LocationConsent = booleanVal;
            }

            int integerVal;
            if (settings.TryGetValue(MovementThresholdKey, out integerVal))
            {
                state.MovementThreshold = integerVal;
            }
            return state;
        }
    }
}
